<template>
  <!-- 登录表单容器 -->
  <div class="login-form-container">
    <!-- 登录方式标签页 -->
    <div class="login-tabs">
      <div 
        :class="['tab-item', { active: currentTab === 'password' }]"
        @click="switchTab('password')"
      >
        <span>密码登录</span>
      </div>
      <div 
        :class="['tab-item', { active: currentTab === 'phone' }]"
        @click="switchTab('phone')"
      >
        <span>手机号</span>
      </div>
      <div 
        :class="['tab-item', { active: currentTab === 'qrcode' }]"
        @click="switchTab('qrcode')"
      >
        <span>二维码</span>
      </div>
    </div>

    <!-- 密码登录模式 -->
    <div v-if="currentTab === 'password'" class="login-mode">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" :validate-on-rule-change="false">
        <el-form-item label-width="0" prop="username">
          <el-input
            v-model="passwordForm.username"
            placeholder="请输入用户名或手机号"
            class="input-box"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label-width="0" prop="password">
          <el-input
            v-model="passwordForm.password"
            placeholder="请输入密码"
            type="password"
            show-password
            class="input-box"
            @keyup.enter="handlePasswordLogin"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item v-if="captchaEnabled" label-width="0" prop="code">
          <div class="captcha-box">
            <el-input
              v-model="passwordForm.code"
              placeholder="请输入验证码"
              class="input-box"
              maxlength="6"
            />
            <img
              :src="captchaImage"
              alt="验证码"
              class="captcha-image"
              @click="refreshCaptcha(true)"
              title="点击刷新"
            />
          </div>
        </el-form-item>

        <!-- 记住我 + 忘记密码 -->
        <div class="check-container remember-pwd">
          <el-checkbox v-model="passwordForm.rememberMe">记住我</el-checkbox>
          <span class="forgot-link" @click="$emit('forgot-password')">忘记密码？</span>
        </div>

        <el-form-item label-width="0">
          <el-button
            :loading="loginLoading"
            type="primary"
            class="login-button"
            @click="handlePasswordLogin"
          >
            {{ loginLoading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 手机号登录模式 -->
    <div v-if="currentTab === 'phone'" class="login-mode">
      <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" :validate-on-rule-change="false">
        <!-- 手机号输入 -->
        <el-form-item label-width="0" prop="phone">
          <el-input
            v-model="phoneForm.phone"
            placeholder="请输入手机号"
            class="input-box"
            clearable
          >
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 短信验证码 -->
        <el-form-item label-width="0" prop="smsCode">
          <div class="sms-box">
            <el-input
              v-model="phoneForm.smsCode"
              placeholder="请输入短信验证码"
              class="input-box"
              maxlength="6"
            />
            <el-button
              :disabled="smsCountdown > 0 || smsSending"
              :loading="smsSending"
              class="sms-button"
              @click="sendPhoneSmsCode"
            >
              {{ smsCountdown > 0 ? `${smsCountdown}s后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label-width="0">
          <el-button
            :loading="loginLoading"
            type="primary"
            class="login-button"
            @click="handlePhoneLogin"
          >
            {{ loginLoading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 二维码登录模式 -->
    <div v-if="currentTab === 'qrcode'" class="login-mode qrcode-mode">
      <!-- 平台选择 - 紧凑型 -->
      <div class="platform-selector-compact">
        <div 
          v-for="platform in qrcodePlatforms" 
          :key="platform.value"
          :class="['platform-btn', { active: selectedPlatform === platform.value }]"
          :style="{ '--platform-color': platform.color }"
          @click="handlePlatformChange(platform.value)"
        >
          <span class="btn-icon-text">{{ platform.iconText }}</span>
          <span class="btn-text">{{ platform.label }}</span>
        </div>
      </div>
      
      <!-- 使用通用的二维码组件 -->
      <QRCodeGenerator
        ref="qrcodeGeneratorRef"
        :content="qrcodeContent"
        :size="180"
        :show-status="false"
        :show-refresh="false"
        :expire-time="60"
        error-correction-level="M"
        :with-logo="true"
        logo-text="扫"
        :platform="selectedPlatform"
        :tip="getPlatformTip(selectedPlatform)"
        @auto-refresh="handleQrcodeAutoRefresh"
        @status-change="handleQrcodeStatusChange"
      />
    </div>

    <!-- 社交登录 - 已隐藏 -->
    <!-- <div class="social-login-section">
      <div class="social-divider">或</div>
      <div class="social-login-container">
        <el-button 
          circle 
          title="微信登录"
          class="social-btn wechat-btn"
          @click="doSocialLogin('wechat')"
        >
          <span style="color: #09b83e; font-weight: bold">微</span>
        </el-button>
        <el-button 
          circle 
          title="QQ登录"
          class="social-btn qq-btn"
          @click="doSocialLogin('qq')"
        >
          <span style="font-weight: bold">Q</span>
        </el-button>
        <el-button 
          circle 
          title="企业微信登录"
          class="social-btn wxwork-btn"
          @click="doSocialLogin('wxwork')"
        >
          <span style="color: #4a90e2; font-weight: bold">企</span>
        </el-button>
      </div>
    </div> -->
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { ElMessage, type FormInstance } from 'element-plus';
import { User, Lock, Iphone, Refresh } from '@element-plus/icons-vue';
import { QRCodeGenerator } from '@tuxing/ui-components';
import {
  login,
  phoneLogin,
  getCodeImg,
  sendSmsCode,
  type LoginParam,
  type PhoneLoginParam,
  type SendSmsParam,
} from '../api/login';
import { useLoginStore } from '../store/login';
import LoginService from '../services/loginService';

defineOptions({
  name: 'LoginForm',
});

// ==================== 状态管理 ====================
const emit = defineEmits(['switch', 'forgot-password']);
const loginStore = useLoginStore();
const { setGlobalState, messageService } = (window as any);

// 当前选中的标签页
const currentTab = ref<'password' | 'phone' | 'qrcode'>('password');

// 验证码相关
const captchaEnabled = ref(false);
const captchaImage = ref('');
const captchaUUID = ref('');
const lastCaptchaTime = ref(0); // 最后一次获取验证码的时间

// 密码登录表单
const passwordFormRef = ref<FormInstance>();
const passwordForm = ref({
  username: '',
  password: '',
  code: '',
  rememberMe: false,
});

// 手机号登录表单
const phoneFormRef = ref<FormInstance>();
const phoneForm = ref({
  phone: '',
  smsCode: '',
});

// 加载状态
const loginLoading = ref(false);
const smsSending = ref(false);

// 短信倒计时
const smsCountdown = ref(0);
let smsInterval: number | null = null;

// 二维码相关
const qrcodeGeneratorRef = ref();
const qrcodeContent = ref('');
const selectedPlatform = ref<'wework' | 'dingtalk' | 'wechat'>('wework');

// 支持的扫码平台 - 使用品牌文字图标（更专业简洁）
const qrcodePlatforms = [
  { 
    value: 'wework', 
    label: '企业微信', 
    iconText: '企',
    color: '#4a90e2' 
  },
  { 
    value: 'dingtalk', 
    label: '钉钉', 
    iconText: '钉',
    color: '#0089ff' 
  },
  { 
    value: 'wechat', 
    label: '微信', 
    iconText: '微',
    color: '#09b83e' 
  }
];

// ==================== 表单验证规则 ====================
const passwordRules = {
  username: [
    { required: true, message: '请输入用户名或手机号', trigger: ['blur', 'change'] },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: ['blur', 'change'] },
  ],
  code: [
    {
      required: captchaEnabled,
      message: '请输入验证码',
      trigger: ['blur', 'change'],
    },
  ],
};

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: ['blur', 'change'],
    },
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: ['blur', 'change'] },
    {
      len: 6,
      message: '验证码应为6位数字',
      trigger: ['blur', 'change'],
    },
  ],
};

// ==================== 方法 ====================

/**
 * 切换标签页
 */
const switchTab = async (tab: 'password' | 'phone' | 'qrcode') => {
  currentTab.value = tab;
  
  // 清空表单并重置验证状态
  await nextTick(); // 等待DOM更新
  
  switch (tab) {
    case 'password':
      passwordForm.value = { username: '', password: '', code: '', rememberMe: false };
      await nextTick();
      passwordFormRef.value?.clearValidate();
      // 恢复记住的用户名
      const rememberedUsername = localStorage.getItem('remembered_username');
      if (rememberedUsername) {
        passwordForm.value.username = rememberedUsername;
        passwordForm.value.rememberMe = true;
      }
      break;
    case 'phone':
      phoneForm.value = { phone: '', smsCode: '' };
      await nextTick();
      phoneFormRef.value?.clearValidate();
      break;
    case 'qrcode':
      // 生成二维码
      generateQrcodeContent();
      break;
  }
};

/**
 * 重置所有表单
 */
const resetAllForms = () => {
  // 清除所有表单数据和验证
  passwordForm.value = { username: '', password: '', code: '', rememberMe: false };
  phoneForm.value = { phone: '', smsCode: '' };
  
  nextTick(() => {
    passwordFormRef.value?.clearValidate();
    phoneFormRef.value?.clearValidate();
  });
};

/**
 * 生成二维码内容
 */
const generateQrcodeContent = () => {
  // 生成唯一的二维码内容（实际应该调用后端API获取）
  qrcodeContent.value = `https://login.datahub.com/qrcode/${Date.now()}`;
  console.log('[LoginForm] 生成二维码内容:', qrcodeContent.value);
};

/**
 * 获取验证码图片
 */
const refreshCaptcha = async (force = false) => {
  try {
    // 防止频繁刷新：5秒内不重复请求（除非强制刷新）
    const now = Date.now();
    if (!force && lastCaptchaTime.value && (now - lastCaptchaTime.value) < 5000) {
      console.log('[LoginForm] 验证码刷新过于频繁，已跳过');
      return;
    }

    lastCaptchaTime.value = now;
    const response = await getCodeImg();
    captchaEnabled.value = response.data.captchaEnabled;
    // 如果图片已包含 data:image 前缀
    if (response.data.img?.startsWith('data:image')) {
      captchaImage.value = response.data.img;
    } else {
      captchaImage.value = `data:image/gif;base64,${response.data.img}`;
    }
    captchaUUID.value = response.data.uuid;

    // 缓存验证码到 sessionStorage（5分钟有效期）
    sessionStorage.setItem('login-captcha-cache', JSON.stringify({
      img: captchaImage.value,
      uuid: captchaUUID.value,
      enabled: captchaEnabled.value
    }));
    sessionStorage.setItem('login-captcha-time', now.toString());
    
    console.log('[LoginForm] 验证码已获取并缓存');
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
};

/**
 * 密码登录
 */
const handlePasswordLogin = async () => {
  try {
    await passwordFormRef.value?.validate();

    loginLoading.value = true;

    const loginParam: LoginParam = {
      username: passwordForm.value.username,
      password: passwordForm.value.password,
      code: captchaEnabled.value ? passwordForm.value.code : undefined,
      uuid: captchaEnabled.value ? captchaUUID.value : undefined,
      grantType: 'password',
      clientId: 'web-app',
    };

    const response = await login(loginParam);

    // 验证响应数据
    if (!response || !response.data) {
      throw new Error('登录响应数据格式错误');
    }

    // 使用 LoginService 保存登录信息
    const loginState = LoginService.saveLoginInfo(response.data, 'manual');

    // 保存到 Pinia store
    await loginStore.login({
      token: response.data.access_token,
      refreshToken: response.data.refresh_token || null,
      userInfo: response.data.user_info || loginState.userInfo,
    });

    // 保存记住密码
    if (passwordForm.value.rememberMe) {
      localStorage.setItem('remembered_username', passwordForm.value.username);
    } else {
      localStorage.removeItem('remembered_username');
    }

    // 设置全局状态
    if (setGlobalState) {
      setGlobalState({
        user: loginState.userInfo,
        token: loginState.token,
        isLogin: true,
      });
    }

    ElMessage.success('登录成功');

    // 重定向到主应用
    redirectToMainApp(loginState.token || response.data.access_token);
  } catch (error: any) {
    console.error('登录失败:', error);
    // ✅ HTTP拦截器已经自动显示错误，这里不需要再显示
    // 如果需要自定义错误处理，可以在 login() 调用时设置 errorHandling: 'manual'
    
    // 登录失败后强制刷新验证码
    if (captchaEnabled.value) {
      refreshCaptcha(true);
    }
  } finally {
    loginLoading.value = false;
  }
};

/**
 * 发送手机号登录短信
 */
const sendPhoneSmsCode = async () => {
  try {
    if (!phoneForm.value.phone) {
      ElMessage.warning('请先输入手机号');
      return;
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phoneForm.value.phone)) {
      ElMessage.error('请输入有效的手机号');
      return;
    }

    smsSending.value = true;

    const sendParam: SendSmsParam = {
      phone: phoneForm.value.phone,
      type: 'login',
    };

    await sendSmsCode(sendParam);

    ElMessage.success('短信验证码已发送');

    // 启动倒计时 (60秒)
    smsCountdown.value = 60;
    smsInterval = window.setInterval(() => {
      smsCountdown.value--;
      if (smsCountdown.value <= 0) {
        smsCountdown.value = 0;
        if (smsInterval) clearInterval(smsInterval);
      }
    }, 1000);
  } catch (error: any) {
    ElMessage.error(error?.message || '发送短信失败');
  } finally {
    smsSending.value = false;
  }
};

/**
 * 手机号登录
 */
const handlePhoneLogin = async () => {
  try {
    await phoneFormRef.value?.validate();

    loginLoading.value = true;

    const phoneLoginParam: PhoneLoginParam = {
      phone: phoneForm.value.phone,
      smsCode: phoneForm.value.smsCode,
      grantType: 'sms',
      clientId: 'web-app',
    };

    const response = await phoneLogin(phoneLoginParam);

    // 验证响应数据
    if (!response || !response.data) {
      throw new Error('登录响应数据格式错误');
    }

    // 使用 LoginService 保存登录信息
    const loginState = LoginService.saveLoginInfo(response.data, 'manual');

    // 保存到 Pinia store
    await loginStore.login({
      token: response.data.access_token,
      refreshToken: response.data.refresh_token || null,
      userInfo: response.data.user_info || loginState.userInfo,
    });

    // 设置全局状态
    if (setGlobalState) {
      setGlobalState({
        user: loginState.userInfo,
        token: loginState.token,
        isLogin: true,
      });
    }

    ElMessage.success('登录成功');

    // 重定向到主应用
    redirectToMainApp(loginState.token || response.data.access_token);
  } catch (error: any) {
    console.error('手机号登录失败:', error);
    // ✅ HTTP拦截器已经自动显示错误，这里不需要再显示
  } finally {
    loginLoading.value = false;
  }
};

/**
 * 获取平台提示文字
 */
const getPlatformTip = (platform: 'wework' | 'dingtalk' | 'wechat') => {
  const tips = {
    wework: '使用企业微信扫码',
    dingtalk: '使用钉钉扫码',
    wechat: '使用微信扫码'
  };
  return tips[platform];
};

/**
 * 平台切换
 */
const handlePlatformChange = (platform: 'wework' | 'dingtalk' | 'wechat') => {
  if (selectedPlatform.value === platform) return; // 避免重复点击
  
  selectedPlatform.value = platform;
  // 切换平台时重新生成二维码
  generateQrcodeContent();
  
  // 等待 DOM 更新后刷新二维码组件
  nextTick(() => {
    qrcodeGeneratorRef.value?.refresh();
  });
};

/**
 * 二维码自动刷新回调
 */
const handleQrcodeAutoRefresh = () => {
  console.log('[LoginForm] 二维码60秒自动刷新');
  // 生成新的二维码内容
  generateQrcodeContent();
};

/**
 * 二维码状态变化回调
 */
const handleQrcodeStatusChange = (status: string) => {
  console.log('[LoginForm] 二维码状态变化:', status);
  
  // 模拟扫码成功后的登录流程
  if (status === 'success') {
    ElMessage.success('扫码成功，正在登录...');
    // 这里应该调用后端API确认登录
    // 暂时使用模拟数据
    setTimeout(() => {
      const mockLoginData = {
        access_token: 'mock_qrcode_token_' + Date.now(),
        refresh_token: 'mock_refresh_token',
        user_info: {
          userId: '1',
          username: 'qrcode_user',
          nickname: '扫码用户',
        },
      };
      
      const loginState = LoginService.saveLoginInfo(mockLoginData, 'manual');
      redirectToMainApp(loginState.token || mockLoginData.access_token);
    }, 1000);
  }
};

/**
 * 社交登录
 */
const doSocialLogin = (type: string) => {
  console.log('社交登录:', type);
  ElMessage.info('正在跳转到 ' + type + ' 登录...');
  // 实现社交登录逻辑
};

/**
 * 重定向到主应用
 */
const redirectToMainApp = (token: string) => {
  // 获取 redirect 参数（从主应用传过来的完整URL）
  const currentUrl = window.location.href;
  const urlParams = new URLSearchParams(window.location.search);
  const redirectUrl = urlParams.get('redirect');

  console.log('========== 登录跳转调试 ==========');
  console.log('[LoginForm] 当前完整URL:', currentUrl);
  console.log('[LoginForm] URL Search 参数:', window.location.search);
  console.log('[LoginForm] 解析到的 redirectUrl:', redirectUrl);
  console.log('[LoginForm] Token:', token);
  
  // 🔧 验证 localStorage 中的 token
  const savedToken = localStorage.getItem('token');
  const savedTuxingToken = localStorage.getItem('tuxing_login_token');
  console.log('[LoginForm] localStorage 中的 token:', savedToken ? `${savedToken.substring(0, 20)}...` : 'null');
  console.log('[LoginForm] localStorage 中的 tuxing_login_token:', savedTuxingToken ? `${savedTuxingToken.substring(0, 20)}...` : 'null');
  console.log('====================================');

  // 🔧 关键修复：优先使用 Cookie 跨域共享，失败则回退到 URL hash
  console.log('[LoginForm] 🍪 正在保存 token 到跨域 Cookie...');
  
  let cookieSuccess = false;
  
  try {
    // 设置 Cookie，domain=localhost（不包含端口，这样所有 localhost 端口都能访问）
    const expirationDays = 7; // 7天过期
    const expirationDate = new Date();
    expirationDate.setTime(expirationDate.getTime() + expirationDays * 24 * 60 * 60 * 1000);
    
    // 关键：domain=localhost（不带端口号）
    document.cookie = `token=${token}; expires=${expirationDate.toUTCString()}; path=/; domain=localhost; SameSite=Lax`;
    
    // 验证 Cookie 是否设置成功
    const cookies = document.cookie;
    cookieSuccess = cookies.includes('token=');
    
    if (cookieSuccess) {
      console.log('[LoginForm] ✅ Token 已保存到 Cookie (domain=localhost)');
      console.log('[LoginForm] Cookie:', cookies);
    } else {
      console.warn('[LoginForm] ⚠️ Cookie 设置失败，可能被浏览器拒绝');
    }
  } catch (error) {
    console.error('[LoginForm] ❌ Cookie 设置异常:', error);
    cookieSuccess = false;
  }

  // 决定跳转 URL
  let finalUrl = '';
  
  if (redirectUrl) {
    // 如果有 redirect 参数，使用它
    finalUrl = redirectUrl;
    console.log('[LoginForm] ✅ 有 redirect 参数，目标URL:', finalUrl);
  } else {
    // 否则跳转到主应用首页
    finalUrl = getMainAppUrl();
    console.log('[LoginForm] ❌ 没有 redirect 参数，跳转到主应用首页:', finalUrl);
  }
  
  // 🔧 如果 Cookie 失败，则通过 URL hash 传递 token（备用方案）
  if (!cookieSuccess) {
    console.warn('[LoginForm] 🔄 Cookie 不可用，使用 URL hash 传递 token（备用方案）');
    finalUrl = `${finalUrl}#token=${encodeURIComponent(token)}`;
  }
  
  // 延迟200ms确保数据写入完成
  setTimeout(() => {
    console.log('[LoginForm] 🚀 正在跳转到:', finalUrl);
    window.location.href = finalUrl;
  }, 200);
};

/**
 * 获取主应用URL
 */
const getMainAppUrl = (): string => {
  // 开发环境
  if (import.meta.env.DEV) {
    return 'http://localhost:3000';
  }
  // 生产环境
  return window.location.origin;
};

// ==================== 生命周期 ====================
onMounted(() => {
  // 清除所有验证状态
  nextTick(() => {
    passwordFormRef.value?.clearValidate();
    phoneFormRef.value?.clearValidate();
  });

  // 检查验证码是否已存在且未过期（通过 sessionStorage 缓存）
  const cachedCaptcha = sessionStorage.getItem('login-captcha-cache');
  const cachedTime = sessionStorage.getItem('login-captcha-time');
  
  if (cachedCaptcha && cachedTime) {
    const timeDiff = Date.now() - parseInt(cachedTime);
    // 验证码缓存5分钟有效
    if (timeDiff < 5 * 60 * 1000) {
      try {
        const cached = JSON.parse(cachedCaptcha);
        captchaImage.value = cached.img;
        captchaUUID.value = cached.uuid;
        captchaEnabled.value = cached.enabled;
        lastCaptchaTime.value = parseInt(cachedTime);
        console.log('[LoginForm] 使用缓存的验证码');
      } catch (e) {
        // 缓存解析失败，重新获取
        refreshCaptcha();
      }
    } else {
      // 缓存过期，重新获取
      refreshCaptcha();
    }
  } else {
    // 没有缓存，首次获取
    refreshCaptcha();
  }

  // 加载记住的用户名
  const rememberedUsername = localStorage.getItem('remembered_username');
  if (rememberedUsername) {
    passwordForm.value.username = rememberedUsername;
    passwordForm.value.rememberMe = true;
  }
});

onBeforeUnmount(() => {
  // 清理短信倒计时
  if (smsInterval) {
    clearInterval(smsInterval);
  }
  
  // 注意：不清除验证码缓存，因为用户可能在登录/注册之间切换
  // 验证码缓存会在5分钟后自动过期或页面关闭时清除
});
</script>

<style lang="less" scoped>
// ==================== LESS 变量 ====================
// 使用 CSS 变量来支持主题切换
@primary: var(--theme-primary, #667eea);
@primary-light: var(--theme-primary-light, #e6f7ff);
@primary-dark: var(--theme-primary-dark, #5568d3);
@success: #52c41a;
@warning: #faad14;
@error: #f5222d;
@text-primary: #1f2937;
@text-secondary: #6b7280;
@text-tertiary: #9ca3af;
@border-color: #e5e7eb;
@bg-light: #f9fafb;
@white: #ffffff;

// ==================== 登录表单容器 ====================
.login-form-container {
  width: 100%;
  max-width: 400px;
  padding: 0;
  
  // 输入框允许选择文本，其他元素不允许
  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    user-select: text;
    -webkit-user-select: text;
  }
}

// ==================== 登录标签页 ====================
// 登录标签页 - 清爽风格
.login-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  border-bottom: 1px solid #d1d5db;
  user-select: none;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 12px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #57606a;
    cursor: pointer;
    border-radius: 0;
    border: none;
    border-bottom: 2px solid transparent;
    transition: all 0.15s ease;
    position: relative;
    bottom: -1px;
    user-select: none;
    white-space: nowrap;

    &:hover:not(.active) {
      color: #24292f;
      border-bottom-color: #d1d5db;
    }

    &.active {
      color: #24292f;
      border-bottom-color: var(--theme-primary, #667eea);
      font-weight: 600;
    }
  }
}

// ==================== 登录模式 ====================
.login-mode {
  animation: fadeInUp 0.5s ease-out;

  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 18px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

// ==================== 输入框样式 - 行业标准 ====================
.input-box {
  :deep(.el-input__wrapper) {
    min-height: 48px;
    padding: 10px 14px;
    border-radius: 8px;
    background: #ffffff;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
    border: 1.5px solid #e1e4e8;
    transition: all 0.15s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      border-color: #b1b5ba;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    }

    &.is-focus {
      background: #ffffff;
      border-color: var(--theme-primary, #667eea);
      border-width: 2px;
      padding: 9px 13px;
      box-shadow: 
        0 0 0 3px color-mix(in srgb, var(--theme-primary, #667eea) 12%, transparent),
        0 2px 4px rgba(0, 0, 0, 0.1);
      transform: translateY(-1px);
    }
  }

  :deep(.el-input__prefix) {
    color: #57606a;
    font-size: 18px;
  }

  :deep(.el-input__inner) {
    font-size: 15px;
    color: #24292f;
    line-height: 1.6;

    &::placeholder {
      color: #8c959f;
      font-size: 15px;
    }
  }
}

// ==================== 验证码框 ====================
.captcha-box {
  display: flex;
  gap: 12px;
  align-items: center;

  .input-box {
    flex: 1;
  }

  .captcha-image {
    width: 110px;
    height: 44px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
    border: 1px solid #dcdfe6;

    &:hover {
      transform: scale(1.02);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      border-color: #c0c4cc;
    }
  }
}

// ==================== 短信验证码框 ====================
.sms-box {
  display: flex;
  gap: 12px;
  align-items: center;

  .input-box {
    flex: 1;
  }

  .sms-button {
    flex-shrink: 0;
    height: 44px;
    padding: 0 20px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    background: #ffffff;
    color: var(--theme-primary, #667eea);
    border: 1px solid #e8e8e8;
    transition: all 0.2s ease;
    white-space: nowrap;
    user-select: none;

    &:hover:not(:disabled) {
      background: var(--theme-primary, #667eea);
      color: #ffffff;
      border-color: var(--theme-primary, #667eea);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
      transform: translateY(-1px);
    }

    &:disabled {
      background: #f5f5f5;
      color: #bfbfbf;
      border-color: #e8e8e8;
      cursor: not-allowed;
    }
  }
}

// ==================== 记住密码 ====================
.check-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  font-size: 13px; /* 稍微减小字体 */
  user-select: none; /* 记住我区域不可选择 */

  :deep(.el-checkbox) {
    .el-checkbox__label {
      color: @text-secondary;
      font-size: 13px; /* 与容器字体一致 */
      user-select: none;
    }

    .el-checkbox__input.is-checked .el-checkbox__inner {
      background-color: @primary;
      border-color: @primary;
    }
  }
}

.remember-pwd {
  .forgot-link {
    color: @primary;
    cursor: pointer;
    font-weight: 500;
    transition: all 0.3s;

    &:hover {
      color: @primary-dark;
      text-decoration: underline;
    }
  }
}

// ==================== 登录按钮 ====================
.login-button {
  width: 100%;
  height: 44px;
  padding: 0 24px;
  font-size: 15px;
  font-weight: 500;
  border-radius: 6px;
  background: var(--theme-primary, #667eea);
  border: none;
  color: #ffffff;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;

  &:hover:not(:disabled) {
    background: color-mix(in srgb, var(--theme-primary, #667eea) 90%, white);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  &:active:not(:disabled) {
    transform: translateY(0);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

// ==================== 二维码模式 ====================
.qrcode-mode {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0;
  min-height: 320px;
  width: 100%;

  // 平台选择器 - 行业标准样式
  .platform-selector-compact {
    display: flex;
    gap: 8px;
    margin: 0 auto 24px;
    width: 100%;
    max-width: 340px;
    flex-shrink: 0;

    .platform-btn {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 6px;
      padding: 12px 8px;
      border-radius: 8px;
      cursor: pointer;
      background: #fff;
      border: 1px solid #e0e0e0;
      transition: all 0.2s ease;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);

      .btn-icon-text {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 28px;
        height: 28px;
        line-height: 28px;
        font-size: 18px;
        font-weight: 600;
        color: #999;
        transition: all 0.2s ease;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.04);
      }

      .btn-text {
        font-size: 13px;
        font-weight: 500;
        color: #666;
        line-height: 18px;
        height: 18px;
        transition: color 0.2s ease;
      }

      &:hover:not(.active) {
        border-color: var(--platform-color, @primary);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        transform: translateY(-1px);

        .btn-icon-text {
          color: @white;
          background: var(--platform-color, @primary);
        }

        .btn-text {
          color: var(--platform-color, @primary);
        }
      }

      &.active {
        background: var(--platform-color, @primary);
        border-color: var(--platform-color, @primary);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
        transform: translateY(-1px);

        .btn-text {
          color: @white;
          font-weight: 500;
        }

        .btn-icon-text {
          color: var(--platform-color, @primary);
          background: @white;
        }
      }
    }
  }

  // 确保二维码组件完全居中
  :deep(.tuxing-qrcode-generator) {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}

// ==================== 社交登录 ====================
.social-login-section {
  margin-top: 16px;
  padding-top: 0;
  border-top: none;

  .social-divider {
    text-align: center;
    color: @text-tertiary;
    font-size: 13px;
    margin-bottom: 14px;
    position: relative;

    &::before,
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      width: 38%;
      height: 1px;
      background: rgba(0, 0, 0, 0.08);
    }

    &::before {
      left: 0;
    }

    &::after {
      right: 0;
    }
  }

  .social-login-container {
    display: flex;
    justify-content: center;
    gap: 20px;

    .social-btn {
      width: 44px;
      height: 44px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.95);
      border: 1px solid rgba(0, 0, 0, 0.06);
      transition: all 0.2s ease;
      font-size: 18px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
        background: @white;
      }
    }
  }
}

// ==================== 动画 ====================
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
